package development.socket;

import java.util.Vector;

import state.AlertListener;
import state.GameAlert;
import state.GameGlobal;
import state.ResourceRms;
import state.Transformer;
import state.md5.MD5;
import state.socket.ClientConnection;
import state.socket.DataPackage;
import state.util.GameStringUtils;
import state.util.Hashtable;
import state.util.TwoDimensionInt;
import state.util.array.StringArray;
import development.Constants;
import development.FrmChooseApp;
import development.Global;
import development.Rms;
import development.bean.User;
import development.group.FrmGroupMenu;
import development.listener.ConnectionDoneListener;
import development.listener.SMSServiceCommandListener;
import development.listener.SMSSystemCommandListener;

public class SocketClientUtil implements AlertListener {
  public static final int TIME_OUT = 30000; // 10s

  private static SocketClientUtil instance = new SocketClientUtil();

  public void alertEventPerform(int alertType, int eventType, int alertId) {
    switch (alertId) {
    case 99:
      Global.alert.showAlert(instance, GameAlert.OK_TYPE, "Kết nối thất bại");
      break;
    case 98:
      Global.alert.showAlert(instance, GameAlert.OK_TYPE, "Vào phòng thất bại");
      break;
    case 97:
      Global.alert.showAlert(instance, GameAlert.OK_TYPE, "Vào bàn thất bại");
      break;
    case 96:
      Global.alert.showAlert(instance, GameAlert.OK_TYPE, "Bắt đầu game thất bại");
      break;
    }
  }

  public static void connectToServerForAuthenticate(AuthenticateHandle authenticateHandle) {
    if (Global.authenClient != null) {
      Global.authenClient.detroy();
    }
    Global.authenClient = new ClientConnection(Constants.LOGIN_SERVER, Constants.PORT, authenticateHandle, Global.HEART_BREATH_SEQUENCE_TIME);
    Global.authenticateHandle.addListener(new ConnectionDoneListener());
    Global.authenticateHandle.addListener(new SMSSystemCommandListener());
    Global.authenticateHandle.addListener(new SMSServiceCommandListener());
  }

  public static void connectToGameServer(String url, int port, GameActionHandle gameActionHandle) {
    if (Global.gameActionClient != null) {
      Global.gameActionClient.detroy();
    }
    GameActionHandle.isLoginSuccess = false;
    Global.gameActionClient = new ClientConnection(url, port, gameActionHandle, Global.HEART_BREATH_SEQUENCE_TIME);
  }

  public static void connectToChatServer(String url, int port, ChatHandle chatHandle) {
    if (Global.chatClient != null) {
      Global.chatClient.detroy();
    }
    Global.chatClient = new ClientConnection(url, port, chatHandle, Global.HEART_BREATH_SEQUENCE_TIME);
  }

  public static void connectToAppServer(String url, int port, AppHandle appHandle) {
    if (Global.appClient != null) {
      Global.appClient.detroy();
    }
    Global.appClient = new ClientConnection(url, port, appHandle, Global.HEART_BREATH_SEQUENCE_TIME);
  }

  public static void checkForUpdate(String version, int providerId) {
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.CHECK_VERSION_REQUEST);
    dataPackage.putString(Constants.VERSION);
    dataPackage.putInt(Global.provider.getId());
    dataPackage.putString(Constants.GAME_VERSION_INFO);
    Global.authenClient.write(dataPackage);
  }

  public static void requestNumberOfResource(String category) {
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.NUMBER_OF_TOTAL_RESOURCE_REQUEST);
    dataPackage.putString(category);
    Global.authenClient.write(dataPackage);
  }

  public static void requestResource(String category) {
    Hashtable resourceByCategory = (Hashtable) Global.resourceCategory.get(category);
    if (resourceByCategory == null) {
      resourceByCategory = ResourceRms.loadMasterRecord(category);
      if (resourceByCategory == null) {
        resourceByCategory = new Hashtable();
      }
      Global.resourceCategory.put(category, resourceByCategory);
    }

    Vector downloadedReources = new Vector();
    if (resourceByCategory != null) {
      Vector images = resourceByCategory.keys();
      for (int i = 0; i < images.size(); i++) {
        downloadedReources.addElement(images.elementAt(i));
      }
    }

    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.DOWNLOADED_RESOURCE_LIST_REQUEST);
    dataPackage.putString(category);
    dataPackage.putInt(downloadedReources.size());
    for (int i = 0; i < downloadedReources.size(); i++) {
      dataPackage.putString(String.valueOf(downloadedReources.elementAt(i)));
    }
    Global.authenClient.write(dataPackage);
  }

  public static void requestImage(String category, String imageName) {
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.IMAGE_REQUEST);
    dataPackage.putString(category);
    dataPackage.putString(imageName);
    Global.authenClient.write(dataPackage);
  }

  public static void requestDownloadUrl() {
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.DOWNLOAD_URL_REQUEST);
    dataPackage.putInt(Global.provider.getId());
    Global.authenClient.write(dataPackage);
  }
  
  public static void requestHelpContent(String helpId) {
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.HELP_CONTENT_REQUEST);
    dataPackage.putString(helpId);
    Global.authenClient.write(dataPackage);
  }

  public static void joinChatRoom(TwoDimensionInt chatLocation240x320, TwoDimensionInt chatLocation320x240) {
    // Create room name
    StringBuffer roomName = new StringBuffer(Global.currentGameService.getId());
    roomName.append("_");
    roomName.append(Global.currentGame.getId());
    roomName.append("_");
    roomName.append(Global.currentRoom.getId());
    roomName.append("_");
    roomName.append(Global.currentTable.getId());

    // Join chat room
    SocketClientUtil.createOrJoinChatRoom(roomName.toString(), "");

    // Init chat component
    if (Global.chatComponent != null) {
      Global.chatComponent.setCurrentRoomId(roomName.toString());
      Global.initChatComponent(chatLocation240x320, chatLocation320x240);
    }
  }

  /**
   * Tiến hành tự động login ngầm mà người sử dụng ko biết
   */
  // public static void privateLogin() {
  // Global.currentUser.setName(Global.loginInfo.getUserName());
  // Global.currentUser.setPasswordMd5(MD5.toBase64(Global.loginInfo.getPassword().getBytes()));
  // SocketClientUtil.startAuthenticateRequest(Global.currentUser.getName());
  // }

  public static void register(String username, String password) {
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.REGISTER_REQUEST);
    dataPackage.putString(username);
    dataPackage.putString(MD5.toBase64(GameStringUtils.toByteArrayUTF8(password)));
    dataPackage.putInt(Global.provider.getId());
    Global.authenClient.write(dataPackage);
  }

  public static void login(boolean isShowLoading) {
    Global.currentUser.setName(Global.loginInfo.getUserName());
    Global.currentUser.setPasswordMd5(MD5.toBase64(GameStringUtils.toByteArrayUTF8(Global.loginInfo.getPassword())));

    // Nếu user đã được xác nhận rồi thì chuyển tiếp sang form tiếp theo
    if (Global.loginInfo.getUserName().equals(Global.validedUsername) && (Global.session != null)) {
      GameGlobal.nextState1(FrmGroupMenu.instance(), null, Transformer.TRANSFORM_WITH_LOADING_FORM);
    } else { // Nếu là user chưa được xác nhận thì tiến hành xác nhận user
      Global.waitingToValidUsername = Global.loginInfo.getUserName();
      if (isShowLoading) {
        GameGlobal.alert.showAlert2(instance, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang đăng nhập...", 99).setAlertTimeOut(TIME_OUT);
      }
      SocketClientUtil.authenticateByPassword(Global.currentUser.getName(), Global.currentUser.getPasswordMd5(), "salt");
    }
  }

  public static void signOut() {
    if (Global.session != null) {
      DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.SIGN_OUT_REQUEST);
      dataPackage.putString(Global.session.getUsername());
      dataPackage.putString(MD5.toBase64(GameStringUtils.toByteArrayUTF8(Global.session.getId())));
      Global.authenClient.write(dataPackage);
      Global.session = null;
      Rms.deleteSession();
    }

    if (Global.gameActionClient != null) {
      Global.gameActionClient.detroy();
      Global.gameActionClient = null;
    }

    if (Global.appClient != null) {
      Global.appClient.detroy();
      Global.appClient = null;
    }

    if (Global.chatClient != null) {
      Global.chatClient.detroy();
      Global.chatClient = null;
    }
  }

  public static void startAuthenticateRequest(String username) {
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.AUTHENTICATE_REQUEST);
    dataPackage.putString(username);
    Global.authenClient.write(dataPackage);
  }

  public static void authenticateByPassword(String username, String passwordMd5, String salt) {
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.AUTHENTICATE_WITH_PASSWORD_REQUEST);
    dataPackage.putString(username);
    dataPackage.putString(MD5.toBase64(GameStringUtils.toByteArrayUTF8((username + passwordMd5))));
    String sessionId = Rms.getSession(username);
    if (sessionId != null) {
      dataPackage.putString(sessionId);
    }
    Global.authenClient.write(dataPackage);
  }

  public static void authenToServerBySessionId(ClientConnection client, String username, String sessionId, String salt) {
    String encodedData = MD5.toBase64(GameStringUtils.toByteArrayUTF8((sessionId + salt)));
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.AUTHENTICATE_WITH_SESSION_ID_REQUEST);
    dataPackage.putString(username);
    dataPackage.putString(encodedData);
    client.write(dataPackage);
  }

  public static void changePassword(String username, String oldPassword, String newPassword) {
    GameGlobal.alert.showAlert2(instance, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang đổi mật khẩu...", 99).setAlertTimeOut(TIME_OUT);

    String oldPassMd5 = MD5.toBase64(GameStringUtils.toByteArrayUTF8(oldPassword));
    String newPassMd5 = MD5.toBase64(GameStringUtils.toByteArrayUTF8(newPassword));

    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.CHANGE_PASSWORD_REQUEST);
    dataPackage.putString(username);
    dataPackage.putString(oldPassMd5);
    dataPackage.putString(newPassMd5);
    Global.authenClient.write(dataPackage);
  }
  
  public static void sendDeviceInfo() {
    String clientDiviceName = System.getProperty("microedition.platform");
    if ((clientDiviceName != null) && (clientDiviceName.length() > 0)) {
      DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.CLIENT_DEVICE_NAME_REQUEST);
      dataPackage.putString(clientDiviceName);
      Global.authenClient.write(dataPackage);
    }
  }

  public static void requestSMSSystemCommand(int providerId) {
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.SMS_SYSTEM_COMMAND_REQUEST);
    dataPackage.putInt(providerId);
    Global.authenClient.write(dataPackage);
  }

  public static void requestUserInfo(String username) {
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.USER_INFO_REQUEST);
    dataPackage.putString(username);
    Global.authenClient.write(dataPackage);
  }

  public static void startAuthenToServer(ClientConnection client, String username) {
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.AUTHENTICATE_REQUEST);
    dataPackage.putString(username);
    client.write(dataPackage);
  }

  public static void gameServiceListRequest() {
    Global.authenClient.write(DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.GAME_SERVICE_LIST_REQUEST));
  }

  public static void changeUserInfoRequest(User user) {
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.CHANGE_USER_INFO_REQUEST);
    dataPackage.putString(user.getGender());
    dataPackage.putString(user.getMobile());
    dataPackage.putString(user.getFullName());
    dataPackage.putString(user.getBirthDay());
    dataPackage.putString(user.getBirthMonth());
    dataPackage.putString(user.getBirthYear());
    dataPackage.putString(user.getEmail());
    dataPackage.putString(user.getAddress());
    dataPackage.putString(user.getStatus());
    Global.authenClient.write(dataPackage);
  }
  
  public static void requestNumberOfUserOnline() {
    Global.authenClient.write(DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.NUMBER_OF_ONLINE_USER_REQUEST));
  }

  // *************** AVATAR FUNCTION *********************** Receive unknown message header
  public static void requestAvatarCategoryList() {
    Global.authenClient.write(DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.AVARAR_CATEGORY_LIST_REQUEST));
  }

  public static void getAvatarByCategory(String category, int beginIndex, int endIndex) {
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.GET_AVATAR_BY_CATEGORY_REQUEST);
    dataPackage.putString(category);
    dataPackage.putInt(beginIndex);
    dataPackage.putInt(endIndex);
    Global.authenClient.write(dataPackage);
  }

  public static void getAvatar(String username, String avatarId) {
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.GET_AVATAR_BY_ID_REQUEST);
    dataPackage.putString(avatarId);
    dataPackage.putString(username);
    Global.authenClient.write(dataPackage);
  }

  public static void changeAvatar(String avatarId) {
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.CHANGE_AVATAR_REQUEST);
    dataPackage.putString(avatarId);
    Global.authenClient.write(dataPackage);
  }

  public static void gameUserCountRequest() {
    Global.gameActionClient.write(DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.GAME_USER_COUNT_REQUEST));
  }

  public static void sendFeedback(String title, String feedback) {
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.FEEDBACK_REQUEST);
    dataPackage.putString(title);
    dataPackage.putString(feedback);
    Global.authenClient.write(dataPackage);
  }

  public static void exchangeRateRequest() {
    Global.authenClient.write(DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.EXCHANGE_RATE_REQUEST));
  }

  public static void changeMoneyToGoldRequest(int moneyToExchange) {
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.CHANGE_MONEY_TO_GOLD_REQUEST);
    dataPackage.putInt(moneyToExchange);
    Global.authenClient.write(dataPackage);
  }

  // ********************************************************

  // *************** GAME - ROOM - TABLE FUNCTION ***********************
  public static void joinGameRequest(String gameId) {
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.JOIN_GAME_REQUEST);
    dataPackage.putString(gameId);
    Global.gameActionClient.write(dataPackage);
  }

  public static void joinRoomRequest(String roomId) {
    Global.alert.showAlert2(instance, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang vào phòng...", 98).setAlertTimeOut(TIME_OUT);
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.JOIN_ROOM_REQUEST);
    dataPackage.putString(roomId);
    Global.gameActionClient.write(dataPackage);
  }

  public static void joinTableRequest(String tableId, String password) {
    Global.alert.showAlert2(instance, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang vào bàn...", 97).setAlertTimeOut(TIME_OUT);
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.JOIN_TABLE_REQUEST);
    dataPackage.putString(tableId);
    dataPackage.putString(password == null ? "" : password);
    Global.gameActionClient.write(dataPackage);
  }

  public static void acceptInviteUserToTable(String tableId) {
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.ACCEPT_USER_TO_TABLE_REQUEST);
    dataPackage.putString(tableId);
    Global.gameActionClient.write(dataPackage);
  }

  public static void autoFindTable() {
    Global.gameActionClient.write(DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.AUTO_FIND_TABLE));
  }

  public static void invitePlay(Vector choosedUsers, String gameId) {
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.INVITE_USER_TO_TABLE_REQUEST);
    dataPackage.putString(gameId);
    dataPackage.putInt(choosedUsers.size());
    for (int i = 0; i < choosedUsers.size(); i++) {
      dataPackage.putString(choosedUsers.elementAt(i).toString());
    }
    Global.gameActionClient.write(dataPackage);
  }

  public static void leaveRoomRequest() {
    Global.gameActionClient.write(DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.LEAVE_ROOM_REQUEST));
  }

  public static void leaveTableRequest() {
    Global.gameActionClient.write(DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.LEAVE_TABLE_REQUEST));
  }

  public static void getRoomList(String gameId) {
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.GET_ROOM_LIST_REQUEST);
    dataPackage.putString(gameId);
    Global.gameActionClient.write(dataPackage);
  }

  public static void getTableList(String roomId) {
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.GET_TABLE_LIST_REQUEST);
    dataPackage.putString(roomId);
    Global.gameActionClient.write(dataPackage);
  }

  public static void sendReady(boolean isReady) {
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.SEND_READY_REQUEST);
    dataPackage.putInt(isReady ? 1 : 0);
    Global.gameActionClient.write(dataPackage);
  }

  public static void configTable(int bid, String password) {
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.CONFIG_TABLE_REQUEST);
    dataPackage.putInt(bid);
    dataPackage.putString(password);
    Global.gameActionClient.write(dataPackage);
  }

  public static void startGame() {
    Global.alert.showAlert2(instance, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang bắt đầu game...", 96).setAlertTimeOut(TIME_OUT);
    Global.gameActionClient.write(DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.START_GAME_REQUEST));
  }

  public static void getUserWantToPlayList(int page) {
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.LIST_USER_WANT_TO_PLAY_REQUEST);
    dataPackage.putInt(page);
    Global.gameActionClient.write(dataPackage);
  }

  public static void listInviteUser(int page) {
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.AUTO_INVITE_LIST_USER_REQUEST);
    dataPackage.putInt(page);
    Global.gameActionClient.write(dataPackage);
  }

  public static void invitePlayFromOutsideGameTable(Vector users, String gameSelected) {
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.AUTO_INVITE_PLAY_FROM_OUT_SIDE_GAME_TABLE);
    dataPackage.putInt(users.size());
    for (int i = 0; i < users.size(); i++) {
      dataPackage.putString(users.elementAt(i).toString());
    }
    dataPackage.putString(gameSelected);
    Global.gameActionClient.write(dataPackage);
  }

  public static void notifyUserWaitingRoomState() {
    Global.gameActionClient.write(DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.AUTO_INVITE_NOTIFY_USER_WAITING_ROOM_STATE_REQUEST));
  }

  public static void kickUserRequest(String userToKick) {
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.KICK_USER_REQUEST);
    dataPackage.putString(userToKick);
    Global.gameActionClient.write(dataPackage);
  }

  public static void requestPlayGameOff() {
    Global.gameActionClient.write(DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.PLAY_GAME_OFF_REQUEST));
  }
  
  public static void outAllGameNotifyRequest() {
    Global.gameActionClient.write(DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.OUT_ALL_GAME_NOTIFY_REQUEST));
  }

  // ********************************************************

  // *************** FRIEND FUNCTION ***********************
  public static void transferMoney(String fromUser, String toUsername, int money) {
    if (toUsername == null || toUsername.equals("")) {
      GameGlobal.alert.showAlert(instance, GameAlert.OK_TYPE, "Người chơi không tồn tại");
      return;
    }
    if (toUsername.equals(Global.currentUser.getName())) {
      GameGlobal.alert.showAlert3(instance, GameAlert.OK_TYPE, StringArray.create1("Không thể tự chuyển tiền", "cho chính mình"));
      return;
    }
    if (money < 0) {
      GameGlobal.alert.showAlert(instance, GameAlert.OK_TYPE, "Số tiền phải lớn hơn 0");
      return;
    }
    if (money > Global.currentUser.getMoney()) {
      money = Global.currentUser.getMoney();
    }
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.TRANSFER_MONEY_REQUEST);
    dataPackage.putString(fromUser);
    dataPackage.putString(toUsername);
    dataPackage.putInt(money);
    Global.authenClient.write(dataPackage);
  }

  public static void addFriendRequest(String toUsername) {
    if (toUsername == null || toUsername.equals("")) {
      GameGlobal.alert.showAlert(instance, GameAlert.OK_TYPE, "Người chơi không tồn tại");
      return;
    }

    if (toUsername.equals(Global.currentUser.getName())) {
      GameGlobal.alert.showAlert3(instance, GameAlert.OK_TYPE, StringArray.create1("Không thể tự kết bạn", "với chính mình" ));
      return;
    }

    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.ADD_FRIEND_REQUEST);
    dataPackage.putString(toUsername);
    Global.authenClient.write(dataPackage);
    GameGlobal.alert.showAlert3(instance, GameAlert.OK_TYPE, StringArray.create1( "Bạn đã gửi yêu cầu", "kết bạn thành công" ));
  }

  public static void addFriendAgree(String fromUsername) {
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.ADD_FRIEND_AGREE_REQUEST);
    dataPackage.putString(fromUsername);
    Global.authenClient.write(dataPackage);
  }

  public static void addFriendDeny(String fromUsername) {
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.ADD_FRIEND_DENY_REQUEST);
    dataPackage.putString(fromUsername);
    Global.authenClient.write(dataPackage);
  }

  public static void requestFriendList(String username) {
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.GET_FRIEND_LIST_REQUEST);
    dataPackage.putString(username);
    Global.authenClient.write(dataPackage);
  }

  public static void removeFriendRequest(String friendName) {
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.REMOVE_FRIEND_REQUEST);
    dataPackage.putString(friendName);
    Global.authenClient.write(dataPackage);
  }

  // ********************************************************

  // *************** CHAT FUNCTION ***********************
  public static void createChatRoom(String roomName, String password, String roomTitle, int maxUser) {
    if (Global.chatClient == null) {
      return;
    }

    password = ("".equals(password) || password == null) ? "" : MD5.toBase64(GameStringUtils.toByteArrayUTF8(password));
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.CHAT_CREATE_ROOM_REQUEST);
    dataPackage.putString(roomName);
    dataPackage.putString(password);
    dataPackage.putString(roomTitle);
    dataPackage.putInt(maxUser);
    Global.chatClient.write(dataPackage);
  }

  public static void createChatRoom(String roomTitle, String password, int maxUser) {
    String roomName = Global.currentUser.getName() + System.currentTimeMillis();
    createChatRoom(roomName, password, roomTitle, maxUser);
  }

  public static void joinChatRoom(String roomName, String password) {
    if (Global.chatClient == null) {
      return;
    }

    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.CHAT_JOIN_CHAT_ROOM_REQUEST);
    dataPackage.putString(roomName);
    dataPackage.putString(password);
    Global.chatClient.write(dataPackage);
  }

  public static void createOrJoinChatRoom(String roomName, String password) {
    if (Global.chatClient == null) {
      return;
    }

    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.CHAT_CREATE_OR_JOIN_ROOM_REQUEST);
    dataPackage.putString(roomName);
    dataPackage.putString(password);
    Global.chatClient.write(dataPackage);
  }

  public static void requestChatRoomList() {
    if (Global.chatClient == null) {
      return;
    }

    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.CHAT_ROOM_LIST_REQUEST);
    Global.chatClient.write(dataPackage);
  }

  public static void sendMessage(String destName, String message) {
    if (Global.chatClient == null) {
      Global.alert.showAlert3(instance, GameAlert.OK_TYPE, StringArray.create1(  "Không có kết nối tới", "máy chủ chat" ));
      return;
    }

    if (Global.chatComponent != null) {
      Global.chatComponent.addMessage(Global.currentUser.getName(), message);
    }

    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.CHAT_SEND_MESSAGE_REQUEST);
    dataPackage.putString(destName);
    dataPackage.putString(message);
    Global.chatClient.write(dataPackage);
  }

  // ********************************************************

  // *************** APP FUNCTION ***********************

  public static void chooseAppRequest(int chooseIndex) {
    Global.appHandle.chooseAppIndex = chooseIndex;
    if (Global.appClient == null) {
      if (Global.appService != null) {
        connectToAppServer(Global.appService.getUrl(), Global.appService.getPort(), Global.appHandle);
      } else {
        GameGlobal.alert.showAlert3(instance, GameAlert.OK_TYPE, StringArray.create1( "Không có thông tin", "máy chủ ứng dụng" ));
      }
    } else {
      FrmChooseApp frmChooseApp = (FrmChooseApp) FrmChooseApp.instance();
      DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.APP_CHOOSE_APP_REQUEST);
      dataPackage.putString(frmChooseApp.APP_ID.get(chooseIndex));
      Global.appClient.write(dataPackage);
    }
  }

  public static void chooseAppRequest(String appId) {
    if (Global.appClient == null) {
      if (Global.appService != null) {
        connectToAppServer(Global.appService.getUrl(), Global.appService.getPort(), Global.appHandle);
      } else {
        GameGlobal.alert.showAlert3(instance, GameAlert.OK_TYPE, StringArray.create1( "Không có thông tin", "máy chủ ứng dụng" ));
      }
    } else {
      DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.APP_CHOOSE_APP_REQUEST);
      dataPackage.putString(appId);
      Global.appClient.write(dataPackage);
    }
  }

  // ********************************************************

  // *************** RANKING FUNCTION ***********************
  public static void requestTopRickest() {
    Global.authenClient.write(DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.RANKING_GET_TOP_RISKEST_REQUEST));
  }

  public static void requestTopLevel() {
    Global.authenClient.write(DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.RANKING_GET_TOP_LEVEL_REQUEST));
  }

  // *************** MESSAGING FUNCTION ***********************
  public static void countInboxMessageUnread(String username) {
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.MESSAGE_UNREAD_COUNT_REQUEST);
    dataPackage.putString(username);
    Global.authenClient.write(dataPackage);
  }

  public static void sendMessageToInbox(String sender, String recipient, String title, String content) {
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.SEND_MESSAGE_REQUEST);
    dataPackage.putString(sender);
    dataPackage.putString(recipient);
    dataPackage.putString(title);
    dataPackage.putString(content);
    Global.authenClient.write(dataPackage);
  }
  
  public static void createSubscription(String service, String command){
    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.CREATED_SUBSCRIPTION_REQUEST);
    dataPackage.putString(service);
    dataPackage.putString(command);
    Global.authenClient.write(dataPackage);
  }
  // ********************************************************
}
